package com.sh.personnel.security.config.filter;

import com.sh.personnel.config.redis.RedisConstant;
import com.sh.personnel.security.config.CustomRequestWrapper;
import com.sh.personnel.security.exception.CaptchaValidateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 邮箱绑定验证过滤器
 * @author 林思浩
 * @date 2020/03/12 15:01
 */
@Component
public class RegisterCodeAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String[] paths = new String[]{"/api/register", "/api/user/email/unbind", "/api/user/email/bind"};
       if(Arrays.asList(paths).contains(request.getRequestURI()) && "POST".equalsIgnoreCase(request.getMethod())) {
            CustomRequestWrapper customRequestWrapper = new CustomRequestWrapper(request);
            HashMap mailCode = customRequestWrapper.getMailCode();
            try {
                validateCode(mailCode);
            } catch (CaptchaValidateException e) {
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);return;
            }
            filterChain.doFilter(customRequestWrapper, response);return;
        }
        filterChain.doFilter(request, response);

    }

    /**
     * 验证验证码
     * @param mailCode
     */
    private void validateCode(HashMap mailCode) {
        String email = (String) mailCode.get("email");
        String code = (String) mailCode.get("code");
        if(StringUtils.isEmpty(email)) throw new CaptchaValidateException("邮箱不能为空");
        if(StringUtils.isEmpty(code)) throw new CaptchaValidateException("验证码不能为空");
        String value = (String) redisTemplate.opsForValue().get(RedisConstant.EMAIL_CAPTCHA + email);
        if(StringUtils.isEmpty(value)) throw new CaptchaValidateException("验证码已过期");
        if(!code.equalsIgnoreCase(value)) throw new CaptchaValidateException("验证码错误");

    }


}
